package controls;


import net.java.games.input.Component;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
import net.java.games.input.Event;
import net.java.games.input.EventQueue;


public class TestGamePad
{
   public static void main(String[] args)
   {
      Controller[] ca = ControllerEnvironment.getDefaultEnvironment()
            .getControllers();
      boolean isGamePadFound = false;
      Controller gamePad = null;

      for (int i = 0; i < ca.length; i++)
      {

         if (ca[i].getType() == Controller.Type.GAMEPAD)
         {

            gamePad = ca[i];
            /* Get the name of the controller */
            System.out.println(ca[i].getName());

            System.out.println("Type: " + ca[i].getType().toString());

            isGamePadFound = true;

            Component[] buttons = ca[i].getComponents();
            System.out.println("Component Count: " + buttons.length);
            for (int j = 0; j < buttons.length; j++)
            {
               System.out.print("Component " + j + ": " + buttons[j].getName() + " Identifer: " + buttons[j].getIdentifier().getName() 
                     + " :");

               if (buttons[j].isAnalog())
               {
                  System.out.println(" Analog");
               }
               else
               {
                  System.out.println(" Digital");
               }

            }
         }

      }
      if (!isGamePadFound)
      {
         System.err.println("GamePad was not found!");
      }
      else
      {
         gamePad.poll();

         for (int i = 0; i < gamePad.getComponents().length; i++)
         {
            System.out.println(gamePad.getComponents()[i].getName() + " : "
                  + gamePad.getComponents()[i].getPollData());
         }
         while (true)
         {
            gamePad.poll();
            EventQueue queue = gamePad.getEventQueue();
            Event event = new Event();
            while(queue.getNextEvent(event)) {
               StringBuffer buffer = new StringBuffer();
              // buffer.append(" at ");
           //    buffer.append(event.getNanos()).append(", ");
               Component comp = event.getComponent();
               buffer.append(comp.getIdentifier().getName()).append(" changed to ");
               float value = event.getValue(); 
               if(comp.isAnalog()) {
                  buffer.append(value);
               } else {
                  if(value > 0.9f) {
                     buffer.append("On " + value);
                  } else {
                     buffer.append("Off " + value);
                  }
               }
               System.out.println(buffer.toString());
            }

         }

      }

   }
}
